package cn.itcast.wanxinp2p.uaa.domain;

import cn.itcast.wanxinp2p.api.account.model.AccountDTO;
import cn.itcast.wanxinp2p.api.account.model.AccountLoginDTO;
import cn.itcast.wanxinp2p.common.domain.RestResponse;
import cn.itcast.wanxinp2p.common.util.StringUtil;
import cn.itcast.wanxinp2p.uaa.agent.AccountApiAgent;
import cn.itcast.wanxinp2p.uaa.common.utils.ApplicationContextHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class IntegrationUserDetailsAuthenticationHandler {

    /**
     * 认证处理
     *
     * @param domain             用户域 ，如b端用户、c端用户等
     * @param authenticationType 认证类型，如密码认证，短信认证等
     * @param token              封装 传递用户名或者密码，或者其他信息
     * @return
     */
    public UnifiedUserDetails authentication(String domain, String authenticationType, UsernamePasswordAuthenticationToken token) {
        //1从客户端获取数据
        //获取账户名称
        String name = token.getName();
        if (StringUtil.isBlank(name)) {
            throw new BadCredentialsException("账户为空");
        }
        //获取密码信息
        String credentials = token.getCredentials().toString();
        if (StringUtil.isBlank(credentials)) {
            throw new BadCredentialsException("密码为空");
        }
//2.调用账户微服务，进行账户、密码校验（Feign接口）
        AccountApiAgent accountApiAgent = (AccountApiAgent) ApplicationContextHelper.getBean(AccountApiAgent.class);
        AccountLoginDTO accountLoginDTO = new AccountLoginDTO();
        accountLoginDTO.setDomain(domain);
        //①指定账户名
        accountLoginDTO.setUsername(name);
        accountLoginDTO.setPassword(credentials);

        //②用的不是账户名登录，使用的是手机号，将手机号封装到username中
        accountLoginDTO.setMobile(name);


        RestResponse<AccountDTO> login = accountApiAgent.login(accountLoginDTO);


        if(login.getCode()!=0){
            throw new BadCredentialsException("登录失败");
        }
        //登录成功，封装后返回数据
        /*
        * 参数1：账户名
        * 参数2：密码
        * 参数3：账户权限  ,这里给的权限为空，暂时没有给
        * */
        UnifiedUserDetails unifiedUserDetails =new UnifiedUserDetails(name,credentials,AuthorityUtils.createAuthorityList());
        unifiedUserDetails.setMobile(accountLoginDTO.getMobile());


        return unifiedUserDetails;
    }

    /**
     * mock  UnifiedUserDetails
     *
     * @param username
     * @return
     */
    private UnifiedUserDetails getUserDetails(String username) {
        Map<String, UnifiedUserDetails> userDetailsMap = new HashMap<>();
        userDetailsMap.put("admin",
                new UnifiedUserDetails("admin", "111111", AuthorityUtils.createAuthorityList("ROLE_PAGE_A", "PAGE_B")));
        userDetailsMap.put("xufan",
                new UnifiedUserDetails("xufan", "111111", AuthorityUtils.createAuthorityList("ROLE_PAGE_A", "PAGE_B")));

        userDetailsMap.get("admin").setDepartmentId("1");
        userDetailsMap.get("admin").setMobile("18611106983");
        userDetailsMap.get("admin").setTenantId("1");
        Map<String, List<String>> au1 = new HashMap<>();
        au1.put("ROLE1", new ArrayList<>());
        au1.get("ROLE1").add("p1");
        au1.get("ROLE1").add("p2");
        userDetailsMap.get("admin").setUserAuthorities(au1);
        Map<String, Object> payload1 = new HashMap<>();
        payload1.put("res", "res1111111");
        userDetailsMap.get("admin").setPayload(payload1);


        userDetailsMap.get("xufan").setDepartmentId("2");
        userDetailsMap.get("xufan").setMobile("18611106984");
        userDetailsMap.get("xufan").setTenantId("1");
        Map<String, List<String>> au2 = new HashMap<>();
        au2.put("ROLE2", new ArrayList<>());
        au2.get("ROLE2").add("p3");
        au2.get("ROLE2").add("p4");
        userDetailsMap.get("xufan").setUserAuthorities(au2);

        Map<String, Object> payload2 = new HashMap<>();
        payload2.put("res", "res222222");
        userDetailsMap.get("xufan").setPayload(payload2);
        return userDetailsMap.get(username);

    }

}
